<template>
  <div id="fileManagePage">

    <a-flex justify="space-between">
      <h2>文件管理</h2>
      <a-space>
        <a-button type="primary" href="/add_file" target="_blank" ghost> <FileAddOutlined />创建文件</a-button>
      </a-space>
    </a-flex>

    <div style="margin-bottom: 16px" />

    <!--    搜索表单-->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="文件名称">
        <a-input v-model:value="searchParams.name" placeholder="输入文件名称" allow-clear />
      </a-form-item>
      <a-form-item label="文件后缀">
        <a-input v-model:value="searchParams.fileFormat" placeholder="输入文件名称" allow-clear />
      </a-form-item>
      <a-form-item name="fillStatus" label="文件状态">
        <a-select
          v-model:value="searchParams.fillStatus"
          style="min-width: 180px"
          placeholder="请选择文件状态"
          :options="FILE_CREATE_STATUS_OPTIONS"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>

    <div style="margin-bottom: 16px" />
    <!--    表格-->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      @resizeColumn="handleResizeColumn"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'userRole'">
          <div v-if="record.userRole === 'admin'">
            <a-tag color="green">管理员</a-tag>
          </div>
          <div v-else>
            <a-tag color="blue">普通用户</a-tag>
          </div>
        </template>
        <template v-if="column.dataIndex === 'tags'">
          <a-space wrap>
            <a-tag v-for="tag in JSON.parse(record.tags || '[]')" :key="tag">
              {{ tag }}
            </a-tag>
          </a-space>
        </template>
        <template v-else-if="column.dataIndex === 'name'">
          {{ record.name }}
        </template>
        <template v-else-if="column.dataIndex === 'fileInfo'">
          <div>特征数： {{ record.features ?? '--' }}</div>
          <div>实例数： {{ record.instances ?? '--' }}</div>
          <div>文件大小： {{ formatSize(record.fileSize) }}</div>
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'fillStatus'">
          <a-tag :color="FILE_CREATE_STATUS_COLOR_ENUM[record.fillStatus]">{{
            record.fillStatus
          }}</a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-popconfirm
              v-if="dataList.length && record.userRole !== 'admin'"
              title="确定删除嘛？"
              @confirm="doDelete(record.id)"
            >
              <a-button danger>删除</a-button>
            </a-popconfirm>
            <a-button type="primary" :href="`/add_file?id=`+record.id">编辑</a-button>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { deleteUserUsingPost, listUserVoByPageUsingPost } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import COS_ENUM from '@/enums/CosEnum.ts'
import { deleteFileUsingPost, listFileByPageUsingPost } from '@/api/fileController.ts'
import { formatSize } from '@/utils'
import { FILE_CREATE_STATUS_COLOR_ENUM, FILE_CREATE_STATUS_ENUM, FILE_CREATE_STATUS_OPTIONS } from '@/constant/file.ts'
import { FileAddOutlined } from '@ant-design/icons-vue'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '文件名称',
    dataIndex: 'name',
  },
  {
    title: '文件后缀',
    dataIndex: 'fileFormat',
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true,
  },
  {
    title: '类型',
    dataIndex: 'category',
  },
  {
    title: '标签',
    dataIndex: 'tags',
  },
  {
    title: '文件信息',
    dataIndex: 'fileInfo',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    ellipsis: true,
  },
  {
    title: '创建状态',
    dataIndex: 'fillStatus',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 定义数据
const dataList = ref<API.FileVO[]>([]) //整体更新
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.FileQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
}) // 局部更新

// 分页参数 (computed 监听值的变化情况，改变则更新)
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})

const fetchData = async () => {
  const res = await listFileByPageUsingPost({
    ...searchParams,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

//表格变化，然后重新获取数据
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 页面加载时获取数据, 请求一次
onMounted(() => {
  fetchData()
})

// 搜索数据
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}

// 删除数据
const doDelete = async (id: string) => {
  if (!id) {
    return
  }
  const res = await deleteFileUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
    visible.value = false
  } else {
    visible.value = false
    message.error('删除失败')
  }
}
function handleResizeColumn(w, col) {
  col.width = w;
}

const visible = ref<boolean>(false)
</script>
